<template>
  <view class="container">
    <!-- 设备信息 -->
    <view class="section">
      <text class="title">设备信息：</text>
      <text>设备ID：{{ targetDeviceAddress }}</text>
      <text>连接状态：{{ connected ? '已连接' : '未连接' }}</text>
    </view>

    <!-- 服务列表 -->
    <view class="section" v-for="(service, sIndex) in services" :key="sIndex">
      <text class="service-title">服务 {{ sIndex + 1 }}：</text>
      <text class="uuid">UUID：{{ service.uuid }}</text>
      <text class="type">{{ service.isPrimary ? '主服务' : '次要服务' }}</text>

      <!-- 特征值列表 -->
      <view v-for="(char, cIndex) in service.characteristics" :key="cIndex" class="characteristic">
        <text class="char-title">特征值 {{ cIndex + 1 }}：</text>
        <text class="uuid">UUID：{{ char.uuid }}</text>
        <text class="props">属性：{{ char.properties }}</text>
        <text v-if="char.properties.includes('通知')" class="notify-status">
          通知状态：{{ char.notifying ? '已开启' : '未开启' }}
        </text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      targetDeviceAddress: '22:34:50:15:15:D8', // 目标设备MAC地址
      connected: false, // 连接状态
      deviceId: '', // 设备ID
      services: [] // 服务列表
    };
  },
  methods: {
    // 初始化蓝牙
    async initBluetooth() {
      try {
        await uni.openBluetoothAdapter();
        console.log('蓝牙初始化成功');
        this.startDiscovery();
      } catch (error) {
        console.error('初始化失败:', error);
      }
    },

    // 开始搜索设备
    startDiscovery() {
      uni.startBluetoothDevicesDiscovery({
        success: () => {
          console.log('开始搜索设备...');
          this.listenDeviceFound();
        },
        fail: (err) => console.error('搜索失败:', err)
      });
    },

    // 监听设备发现事件
    listenDeviceFound() {
      uni.onBluetoothDeviceFound((res) => {
        const devices = res.devices;
        // 根据MAC地址过滤目标设备
        const targetDevice = devices.find(
          (device) =>
            device.deviceId.toLowerCase() === this.targetDeviceAddress.toLowerCase()
        );
        if (targetDevice && !this.connected) {
          console.log('发现目标设备', targetDevice);
          this.connectDevice(targetDevice.deviceId);
        }
      });
    },

    // 连接设备
    async connectDevice(deviceId) {
      uni.stopBluetoothDevicesDiscovery(); // 停止搜索
      try {
        await uni.createBLEConnection({ deviceId });
        console.log('连接成功');
        this.connected = true;
        this.deviceId = deviceId; // 存储设备ID
        this.getServices(deviceId); // 获取服务列表
      } catch (error) {
        console.error('连接失败:', error);
      }
    },

   // 获取服务列表
   async getServices(deviceId) {
     try {
       const res = await uni.getBLEDeviceServices({ deviceId });
       // console.log('获取的服务数据:', res);
   
       // 修正这里：使用res.services而不是res[1].services
       const servicePromises = res[1].services.map(async (service) => { // 修改此行
         try {
           const chars = await uni.getBLEDeviceCharacteristics({
             deviceId,
             serviceId: service.uuid
           });
   console.log(chars[1].characteristics);
           return {
             uuid: service.uuid.toLowerCase(),
             isPrimary: service.isPrimary,
             // 这里也要修正为chars.characteristics
             characteristics: chars[1].characteristics.map((c) => ({
               uuid: c.uuid.toLowerCase(),
               properties: this.parseProperties(c.properties),
               notifying: c.isNotifying
             }))
           };
         } catch (error) {
           console.error(`获取服务 ${service.uuid} 特征值失败:`, error);
           return {
             ...service,
             characteristics: []
           };
         }
       });
   
       this.services = await Promise.all(servicePromises);
       console.log('完整服务特征数据:', this.services);
     } catch (error) {
       console.error('获取服务失败:', error);
       this.services = [];
     }
   },

    // 解析特征值属性
    parseProperties(propertiesObj) {
      const props = [];
      if (propertiesObj.read) props.push('读');
      if (propertiesObj.write) props.push('写');
      if (propertiesObj.writeNoResponse) props.push('写(无响应)');
      if (propertiesObj.notify) props.push('通知');
      if (propertiesObj.indicate) props.push('指示');
      return props.join('/');
    }
  },
  onLoad() {
    this.initBluetooth();
  },
  onUnload() {
    if (this.connected) {
      // 关闭所有特征值通知
      this.services.forEach((service) => {
        service.characteristics.forEach((char) => {
          if (char.properties.includes('通知')) {
            uni.notifyBLECharacteristicValueChange({
              deviceId: this.deviceId,
              serviceId: service.uuid,
              characteristicId: char.uuid,
              state: false
            });
          }
        });
      });

      uni.closeBLEConnection({ deviceId: this.deviceId });
    }
    uni.closeBluetoothAdapter();
  }
};
</script>

<style>
.container {
  padding: 20rpx;
}

.section {
  margin-bottom: 30rpx;
  padding: 15rpx;
  background: #f5f5f5;
  border-radius: 10rpx;
}

.title {
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.service-title {
  font-size: 34rpx;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.uuid {
  font-size: 28rpx;
  color: #666;
  display: block;
  word-break: break-all;
}

.type {
  font-size: 26rpx;
  color: #999;
  display: block;
}

.characteristic {
  margin: 15rpx 0;
  padding: 10rpx;
  background: #fff;
  border-radius: 8rpx;
}

.char-title {
  font-size: 30rpx;
  color: #444;
}

.props {
  color: #09f;
  display: block;
  margin-top: 5rpx;
}

.notify-status {
  color: #f90;
  display: block;
}
</style>